package com.ruoyi.ai.filter;


import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import reactor.util.context.Context;


/**
 * 自定义请求头拦截器，将Header数据封装到线程变量中方便获取
 * 注意：此拦截器会同时验证当前用户有效期自动刷新有效期
 *
 * @author loong
 */
@Component
public class HeaderFilter implements WebFilter {
    /**
     * 用户ID字段
     */
    public static final String DETAILS_USER_ID = "user_id";

    /**
     * 用户名字段
     */
    public static final String DETAILS_USERNAME = "username";

    /**
     * 用户标识
     */
    public static final String USER_KEY = "user_key";

    /**
     * 授权信息字段
     */
    public static final String AUTHORIZATION_HEADER = "Authorization";


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        // 获取请求头中的用户信息
        String userId = request.getHeaders().getFirst(DETAILS_USER_ID);
        String userName = request.getHeaders().getFirst(DETAILS_USERNAME);
        String userKey = request.getHeaders().getFirst(USER_KEY);

        return chain.filter(exchange)
        .contextWrite(Context.of("userId", userId))
        .contextWrite(Context.of("userName", userName))
        .contextWrite(Context.of("userKey", userKey));
    }
}
